//
//  HexMapGeneratingStrategy.cpp
//  DiceWar
//
//  Created by Xiao  Feng on 17/6/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include "HexMapGeneratingStrategy.h"
#include "RandomGenerator.h"
#include <vector>
#include "HexMap.h"

namespace  
{
    const int kStartGridPosX = 30;
    const int kStartGridPosY = 30;
}

HexMapGeneratingStrategy::HexMapGeneratingStrategy() {}
HexMapGeneratingStrategy::~HexMapGeneratingStrategy() {}

void HexMapGeneratingStrategy::generate(int numPlayers, int numDicesPerplayer, HexMap& hexMap)
{
    CCAssert(numPlayers <= kInvalidPlayer, "Too Many Players!");
    if (numPlayers > kInvalidPlayer) return;
    
    generateMapGridLocation(hexMap);
    generateMapGridPlayer(numPlayers, hexMap);
    generateMapGridNumDices(numPlayers, numDicesPerplayer, hexMap);
}

void HexMapGeneratingStrategyNormal::generateMapGridLocation(HexMap& hexMap)
{
    for (int xIndex = 0; xIndex < gameConstants::kHexMapSizeX; xIndex++)
    {
        for (int yIndex = 0; yIndex < gameConstants::kHexMapSizeY; yIndex++)
        {
            const int kOffsetX = kStartGridPosX;
            const int kPositionX = (1.5f * gameConstants::kHexGridSize) * xIndex + kOffsetX;
            const int kOffsetY = (xIndex % 2 == 0) ? kStartGridPosY : kStartGridPosY + gameConstants::kHexGridSize * sqrt(3.0f)/2.0f;
            const int kPositionY = sqrt(3.0f) * gameConstants::kHexGridSize * yIndex + kOffsetY;
            
            HexMapGrid& grid = hexMap.m_map(xIndex, yIndex);
            grid.setPosition(ccp(kPositionX, kPositionY));
            grid.setCoordinate(xIndex, yIndex);
        }
    }
}

void HexMapGeneratingStrategyNormal::generateMapGridPlayer(int numPlayers, HexMap& hexMap)
{
    RandomGenerator random;
    const int totalNumSegments = numPlayers + 1;
    
    for (int xIndex = 0; xIndex < gameConstants::kHexMapSizeX; xIndex++)
    {
        for (int yIndex = 0; yIndex < gameConstants::kHexMapSizeY; yIndex++)
        {
            const int randomNumber = random.getRandomNum(totalNumSegments);
            PlayerType type = getPlayerType(randomNumber, numPlayers);
 
            HexMapGrid& grid = hexMap.m_map(xIndex, yIndex);
            grid.setType((kInvalidPlayer == type) ? HexMapGrid::kWall : HexMapGrid::kFight);
            grid.setPlayerType(type);
        }
    }
}

void HexMapGeneratingStrategyNormal::generateMapGridNumDices(int numPlayers, int numDicesPerPlayer, HexMap& hexMap)
{
    for (int index = 0; index < numPlayers; index++)
    {
        hexMap.addDicesRandomlyToPlayer(numDicesPerPlayer, static_cast<PlayerType>(index));
    }
}

PlayerType HexMapGeneratingStrategyNormal::getPlayerType(int randomNum, int numPlayers)
{
    return (randomNum == numPlayers) ? kInvalidPlayer : static_cast<PlayerType>(randomNum);
}



